<template>
    <div class="addBrand-container" id="combo-add-app">
        <div class="container">
            <el-form :inline="true" :model="ruleForm" :rules="rules" class="demo-ruleForm" label-width="180px"
                ref="ruleForm">
                <div>
                    <el-form-item label="套餐名称:" prop="name">
                        <el-input maxlength="20" placeholder="请填写套餐名称" v-model="ruleForm.name" />
                    </el-form-item>
                    <el-form-item label="套餐分类:" prop="idType">
                        <el-select @change="$forceUpdate()" placeholder="请选择套餐分类" v-model="ruleForm.idType">
                            <el-option :key="index" :label="item.name" :value="item.id"
                                v-for="(item, index) in setMealList" />
                        </el-select>
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="套餐价格:" prop="price">
                        <el-input placeholder="请设置套餐价格" v-model="ruleForm.price" />
                    </el-form-item>
                </div>
                <div>
                    <el-form-item class="setmealFood" label="套餐菜品:">
                        <el-form-item>
                            <div class="addDish">
                                <span @click="openAddDish" class="addBut" v-if="dishTable.length == 0"> + 添加菜品</span>
                                <div class="content" v-if="dishTable.length != 0">
                                    <div @click="openAddDish" class="addBut" style="margin-bottom: 20px">+ 添加菜品</div>
                                    <div class="table">
                                        <el-table :data="dishTable" style="width: 100%">
                                            <el-table-column align="center" label="名称" prop="name" width="180">
                                            </el-table-column>
                                            <el-table-column label="原价" prop="price" width="180">
                                                <template slot-scope="scope">
                                                    {{ Number(scope.row.price) / 100 }}</template>
                                            </el-table-column>
                                            <el-table-column align="center" label="份数" prop="address">
                                                <template slot-scope="scope">
                                                    <el-input-number :max="99" :min="1" label="描述文字" size="small"
                                                        v-model="scope.row.copies"></el-input-number>
                                                </template>
                                            </el-table-column>
                                            <el-table-column align="center" label="操作" prop="address" width="180px;">
                                                <template slot-scope="scope">
                                                    <el-button @click="delDishHandle(scope.$index)" size="small"
                                                        type="text"> 删除
                                                    </el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                    </el-form-item>
                </div>
                <div>
                    <el-form-item class="uploadImg" label="套餐图片:">
                        <el-upload :on-change="onChange" :on-success="handleAvatarSuccess" :show-file-list="false"
                            action="#" class="avatar-uploader" ref="upload" :http-request="upload">
                            <img :src="imageUrl" class="avatar" v-if="imageUrl">
                            <i class="el-icon-plus avatar-uploader-icon" v-else></i>
                        </el-upload>
                    </el-form-item>
                </div>
                <div class="address">
                    <el-form-item label="套餐描述:">
                        <el-input :rows="3" maxlength="200" placeholder="套餐描述，最长200字" type="textarea"
                            v-model="ruleForm.description" />
                    </el-form-item>
                </div>
                <div class="subBox address">
                    <el-form-item>
                        <el-button @click="goBack()"> 取消</el-button>
                        <el-button @click="submitForm('ruleForm', false)" type="primary"> 保存</el-button>
                        <el-button @click="submitForm('ruleForm', true)" class="continue" type="primary"
                            v-if="actionType == 'add'">
                            保存并继续添加套餐
                        </el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>
        <el-dialog :before-close="handleClose" :visible.sync="dialogVisible" class="addDishList" title="添加菜品"
            width="60%">
            <el-input class="seachDish" clearable placeholder="请输入菜品名称进行搜索" size="small" style="width: 250px"
                v-model="value">
                <i @click="seachHandle" class="el-input__icon el-icon-search" slot="prefix" style="cursor: pointer"></i>
            </el-input>
            <!-- <AddDish ref="adddish" :check-list="checkList" :seach-key="seachKey" @checkList="getCheckList" /> -->

            <div class="addDishCon">
                <div class="leftCont">
                    <div class="tabBut" v-show="seachKey.trim() == ''">
                        <span :class="{ act: index == keyInd }" :key="index" @click="checkTypeHandle(index, item.id)"
                            v-for="(item, index) in dishType">{{ item.name }}</span>
                    </div>
                    <div class="tabList">
                        <div class="table">
                            <div style="padding-left:10px" v-if="dishAddList.length == 0">
                                暂无菜品!
                            </div>
                            <el-checkbox-group @change="checkedListHandle" v-if="dishAddList.length > 0"
                                v-model="checkedList">
                                <div :key="index" class="items" v-for="(item, index) in dishAddList">
                                    <el-checkbox :key="index" :label="item">
                                        <div class="item">
                                            <span style="flex: 3;text-align: left">{{ item.dishName }}</span>
                                            <span>{{ item.status == 0 ? '停售' : '在售' }}</span>
                                            <span>￥{{ Number(item.price) / 100 }}</span>
                                        </div>
                                    </el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>
                <div class="ritCont">
                    <div class="tit">
                        已选菜品({{ checkedList.length }})
                    </div>
                    <div class="items">
                        <div :key="ind" class="item" v-for="(item, ind) in checkedList">
                            <span>{{ item.dishName }}</span>
                            <span class="price">￥ {{ Number(item.price) / 100 }} </span>
                            <span @click="delCheck(ind)" class="del">
                                <img alt="" src="./images/btn_clean@2x.png">
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <span class="dialog-footer" slot="footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button @click="addTableList" type="primary">确 定</el-button>
            </span>
        </el-dialog>
    </div>

</template>

<script>
import { getCategoryList, queryDishList, dishUpload, dishDownload } from '@/api/food'
import { addSetmeal, querySetmealById, editSetmeal } from '@/api/combo'
import { qiniuUpload } from '@/api/qiniu'


export default {
    name: 'comboAdd',

    data() {
        return {
            id: '',
            actionType: '',
            value: '',
            setMealList: [],
            seachKey: '',
            dishList: [],
            imageUrl: '',
            actionType: '',
            dishTable: [],
            dialogVisible: false,
            checkList: [],
            ruleForm: {
                name: '',
                categoryId: '',
                price: '',
                code: '',
                image: '',
                description: '',
                dishList: [],
                status: true,
                idType: '',
            },
            dishType: [],
            dishAddList: [],
            dishListCache: [],
            keyInd: 0,
            searchValue: '',
            checkedList: []
        }
    },
    computed: {
        rules() {
            return {
                name: {
                    required: true,
                    message: '请输入套餐名称',
                    trigger: 'blur',
                },
                idType: {
                    required: true,
                    message: '请选择套餐分类',
                    trigger: 'change',
                },
                price: {
                    required: true,
                    // 'message': '请输入套餐价格',
                    validator: (rules, value, callback) => {
                        if (!value) {
                            callback(new Error('请填写菜品价格'))
                        } else {
                            const reg = /^\d+(\.\d{0,2})?$/
                            if (reg.test(value)) {
                                if (value < 10000) {
                                    callback()
                                } else {
                                    callback(new Error('菜品价格小于10000'))
                                }
                            } else {
                                callback(new Error('菜品价格格式只能为数字,且最多保留两位小数'))
                            }
                        }
                    },
                    trigger: 'blur',
                },
            }
        },
    },
    watch: {
        seachKey(value) {
            if (value.trim()) {
                this.getDishForName(this.seachKey)
            }
        },
        checkList(value) {
            this.checkedList = value
        }
    },
    created() {
        this.getDishTypeList()
        this.getDishType()
        this.id = this.$validate.requestUrlParam('id')
        this.actionType = this.id ? 'edit' : 'add'
        if (this.id) {
            this.init()
        }
    },
    mounted() {
    },
    methods: {
        //文件上传
        // upload(param) {
        //     const formData = new FormData()
        //     formData.append('file', param.file)

        //     dishUpload(formData).then(res => {
        //         if (res.code == 1) {
        //             dishDownload(res.data).then(res => {
        //                 this.imageUrl = `data: image/jpeg;base64,${btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`
        //             })
        //             this.ruleForm.image = res.data
        //         } else {
        //             this.$message.error("图片上传失败!")
        //         }
        //     })
        // },

        upload(param) {
            if (this.onUpdate) {
                console.log("======七牛上传回调======");
                const formData = new FormData()
                formData.append('file', param.file)
                console.log(param.file);


                qiniuUpload(formData).then(res => {
                    if (res.code == 1) {
                        console.log("======正在回显======");
                        console.log(res.data);
                        /* https://serms.xyz/aa8fccdece7ab0e.jpg */
                        this.imageUrl = "https://serms.xyz/" + res.data
                        this.ruleForm.image = res.data      //把图片名称存入数据库
                    } else {
                        this.$message.error("图片上传失败!")
                    }
                }).catch(err => {
                    this.$message.error("后端上传接口异常")
                })
            }
        },

        async init() {
            querySetmealById(this.id).then((res) => {
                if (String(res.code) === '1') {
                    this.ruleForm = res.data
                    this.ruleForm.status = res.data.status === '1'
                    this.ruleForm.price = res.data.price / 100
                    // this.imageUrl = `http://192.168.174.100:8888/common/download?name=${res.data.image}`
                    this.imageUrl = `https://serms.xyz/${res.data.image}`
                    // this.imageUrl = `http://localhost:8888/common/download?name=${res.data.image}`
                    this.checkList = res.data.setmealDishes
                    this.dishTable = res.data.setmealDishes
                    this.ruleForm.idType = res.data.categoryId
                    // this.ruleForm.password = ''
                } else {
                    this.$message.error(res.msg || '操作失败')
                }
            })
        },
        seachHandle() {
            this.seachKey = this.value
        },
        // 获取套餐分类
        getDishTypeList() {

            getCategoryList({ 'TypeId': 2 }).then((res) => {
                if (res.code === 1) {
                    this.setMealList = res.data.map((obj) => ({ ...obj, idType: obj.id }))
                } else {
                    this.$message.error(res.msg || '操作失败')
                }
            })
        },
        // 删除套餐菜品
        delDishHandle(index) {
            this.dishTable.splice(index, 1)
            this.checkList.splice(index, 1)
        },

        // 获取添加菜品数据
        getCheckList(value) {
            this.checkList = [...value]
        },

        // 添加菜品
        openAddDish() {
            this.seachKey = ''
            this.dialogVisible = true
            //搜索条件清空，菜品重新查询，菜品类别选第一个重新查询
            this.value = ''
            this.keyInd = 0
            this.getDishList(this.dishType[0].id)
        },
        // 取消添加菜品
        handleClose(done) {
            // this.$refs.adddish.close()
            this.dialogVisible = false
            // this.checkList = JSON.parse(JSON.stringify(this.dishTable))
            // this.dialogVisible = false
        },

        // 保存添加菜品列表
        addTableList() {
            this.dishTable = JSON.parse(JSON.stringify(this.checkList))
            this.dishTable.forEach((n) => {
                n.copies = 1
            })
            this.dialogVisible = false
            // 添加处理逻辑清空选中list
            this.checkList = []
        },
        submitForm(formName, st) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let prams = { ...this.ruleForm }
                    prams.price *= 100
                    prams.setmealDishes = this.dishTable.map((obj) => ({
                        copies: obj.copies,
                        dishId: obj.dishId,
                        name: obj.name,
                        price: obj.price,
                    }))
                    prams.status = this.ruleForm ? 1 : 0
                    prams.categoryId = this.ruleForm.idType
                    if (prams.setmealDishes.length < 1) {
                        this.$message.error('请选择菜品！')
                        return
                    }
                    if (!this.imageUrl) {
                        this.$message.error('请上传套餐图片')
                        return
                    }
                    // delete prams.dishList
                    if (this.actionType == 'add') {
                        delete prams.id
                        addSetmeal(prams)
                            .then((res) => {
                                if (res.code === 1) {
                                    this.$message.success('套餐添加成功！')
                                    if (!st) {
                                        this.goBack()
                                    } else {
                                        this.$refs.ruleForm.resetFields()
                                        this.dishList = []
                                        this.dishTable = []
                                        this.ruleForm = {
                                            name: '',
                                            categoryId: '',
                                            price: '',
                                            code: '',
                                            image: '',
                                            description: '',
                                            dishList: [],
                                            status: true,
                                            id: '',
                                            idType: '',
                                        }
                                        this.imageUrl = ''
                                    }
                                } else {
                                    this.$message.error(res.msg || '操作失败')
                                }
                            })
                            .catch((err) => {
                                this.$message.error('请求出错了：' + err)
                            })
                    } else {
                        delete prams.updateTime
                        editSetmeal(prams)
                            .then((res) => {
                                if (res.code === 1) {
                                    this.$message.success('套餐修改成功！')
                                    this.goBack()
                                } else {
                                    this.$message.error(res.msg || '操作失败')
                                }
                            })
                            .catch((err) => {
                                this.$message.error('请求出错了：' + err)
                            })
                    }
                } else {
                    return false
                }
            })
        },
        handleAvatarSuccess(response, file, fileList) {
            // this.imageUrl = response.data
            if (response.code === 0 && response.msg === '未登录') {
                window.top.location.href = '/backend/page/login/login.html'
            } else {
                // this.imageUrl = `http://localhost:8888/common/download?name=${response.data}`
                // this.imageUrl = `http://192.168.174.100:8888/common/download?name=${response.data}`
                this.imageUrl = `https://serms.xyz/${response.data}`
                this.ruleForm.image = response.data
            }
        },

        onChange(file) {
            if (file) {
                const suffix = file.name.split('.')[1]
                const size = file.size / 1024 / 1024 < 2
                if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                    this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                    this.$refs.upload.clearFiles()
                    return false
                }
                if (!size) {
                    this.$message.error('上传文件大小不能超过 2MB!')
                    return false
                }
                return file
            }
        },
        goBack() {
            const menu = {
                id: '5',
                url: 'home/combo',
                name: '套餐管理',
                goBackFlag: false
            }
            this.$store.dispatch('menuHandle', menu)
        },
        // 获取套餐分类
        getDishType() {
            getCategoryList({ 'TypeId': 2 }).then(res => {
                if (res.code === 1) {
                    this.dishType = res.data
                    this.getDishList(res.data[0].id)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        // 通过套餐ID获取菜品列表分类
        getDishList(id) {
            queryDishList({ categoryId: id }).then(res => {
                if (res.code === 1) {
                    if (res.data.length == 0) {
                        this.dishAddList = []
                        return
                    }
                    let newArr = res.data;
                    newArr.forEach((n) => {
                        n.dishId = n.id
                        n.copies = 1
                        // n.dishCopies = 1
                        n.dishName = n.name
                    })
                    this.dishAddList = newArr
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        // 关键词收搜菜品列表分类
        getDishForName(name) {
            queryDishList({ name }).then(res => {
                if (res.code === 1) {
                    let newArr = res.data
                    newArr.forEach((n) => {
                        n.dishId = n.id
                        n.dishName = n.name
                    })
                    this.dishAddList = newArr
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        checkTypeHandle(ind, id) {
            this.keyInd = ind
            this.getDishList(id)
        },

        checkedListHandle(value) {
            this.getCheckList(this.checkedList)
        },

        open(done) {
            this.dishListCache = JSON.parse(JSON.stringify(this.checkList))
        },

        close(done) {
            this.checkList = this.dishListCache
        },

        // 删除
        delCheck(ind) {
            this.checkedList.splice(ind, 1)
        }
    },
};
</script>

<style lang="css">
@import '@/assets/css/common.css';
@import '@/assets/css/page.css';

.addDish .el-input {
    width: 130px;
}

.addDish .el-input-number__increase {
    border-left: solid 1px #FFE1CA;
    background: #fff3ea;
}

.addDish .el-input-number__decrease {
    border-right: solid 1px #FFE1CA;
    background: #fff3ea;
}

.addDish input {
    border: 1px solid #ffe1ca;
}

.addDish .table {
    border: solid 1px #EBEEF5;
    border-radius: 3px;
}

.addDish .table th {
    padding: 5px 0;
}

.addDish .table td {
    padding: 7px 0;
}

.addDishList .seachDish {
    position: absolute;
    top: 10px;
    right: 20px;
}

.addDishList .el-dialog__body {
    padding: 0;
    border-bottom: solid 1px #ccc;
}

.addDishList .el-dialog__footer {
    padding-top: 27px;
}

.addDish {
    width: 777px;
}

.addDish .addBut {
    background: #ffc200;
    display: inline-block;
    padding: 0px 20px;
    border-radius: 3px;
    line-height: 40px;
    cursor: pointer;
    border-radius: 4px;
    color: #333333;
    font-weight: 500;
}

.addDish .content {
    background: #fafafb;
    padding: 20px;
    border: solid 1px #ccc;
    border-radius: 3px;
}

.addDishCon {
    padding: 0 20px;
    display: flex;
    line-height: 40px;
}

.addDishCon .leftCont {
    display: flex;
    border-right: solid 2px #E4E7ED;
    width: 60%;
    padding: 15px;
}

.addDishCon .leftCont .tabBut {
    width: 110px;
}

.addDishCon .leftCont .tabBut span {
    display: block;
    text-align: center;
    border-right: solid 2px #f4f4f4;
    cursor: pointer;
}

.addDishCon .leftCont .act {
    border-color: #FFC200 !important;
    color: #FFC200 !important;
}

.addDishCon .leftCont .tabList {
    flex: 1;
    padding: 15px;
}

.addDishCon .leftCont .tabList .table {
    border: solid 1px #f4f4f4;
    border-bottom: solid 1px #f4f4f4;
}

.addDishCon .leftCont .tabList .table .items {
    border-bottom: solid 1px #f4f4f4;
    padding: 0 10px;
    display: flex;
}

.addDishCon .leftCont .tabList .table .items .el-checkbox,
.addDishCon .leftCont .tabList .table .items .el-checkbox__label {
    width: 100%;
}

.addDishCon .leftCont .tabList .table .items .item {
    display: flex;
    padding-right: 20px;
}

.addDishCon .leftCont .tabList .table .items .item span {
    display: inline-block;
    text-align: center;
    flex: 1;
}

.addDishCon .ritCont {
    width: 40%;
    padding: 0 15px;
}

.addDishCon .ritCont .item {
    box-shadow: 0px 1px 4px 3px rgba(0, 0, 0, 0.03);
    display: flex;
    text-align: center;
    padding: 0 10px;
    margin-bottom: 20px;
    border-radius: 6px;
    color: #818693;
}

.addDishCon .ritCont .item span:first-child {
    text-align: left;
    color: #20232A;
}

.addDishCon .ritCont .item .price {
    display: inline-block;
    flex: 1;
}

.addDishCon .ritCont .item .del {
    cursor: pointer;
}

.addDishCon .ritCont .item .del img {
    position: relative;
    top: 5px;
    width: 20px;
}

.addDishCon .el-checkbox__label {
    width: 100%;
}

#combo-add-app .setmealFood .el-form-item__label::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}

#combo-add-app .uploadImg .el-form-item__label::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}
</style>